/**
 * 通用工具类
 */
import md5 from '@/common/libs/md5.js'
import cache from '@/common/cache'
import permision from '@/common/permission'
import uploadImage from '@/components/yushijie-ossutil/ossutil/uploadFile.js';
import baseurl from '@/common/config.js'
const $cache = new cache()
var flag = false //防止多次点击
class tools {
	// 验证手机号码  this.$tools.validPhone(要验证的手机号码)
	static validPhone(value) {
		let bol = false
		if (!value) {
			uni.showToast({
				title: '请输入手机号',
				icon: 'none'
			})
			return bol
		} else {
			const reg = /^1\d{10}$/
			if (reg.test(value)) {
				bol = true
			} else {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
			}
		}
		return bol
	};
	// 变量判空  this.$tools.isNull(字符串)
	static isNull(arg) {
		if (arg == null || arg == "undefined" || arg == "" || arg == "null" || arg == "NULL") {
			return true;
		}
		return false;
	};
	// 手机号脱敏（11位）this.$tools.subLastPhone(字符串)
	static subLastPhone(str) {
		str = String(str);
		return str.substr(0, 3) + '****' + str.substr(7); //131****5555
	};
	// 身份证号码脱敏  this.$tools.subLastCard(字符串)
	static subLastCard(idCard) {
		return idCard.replace(idCard.substr(4, 10), '******');
	};

	// md5加密 char 字符串 this.$tools.md5encryption(char)
	static md5encryption(char) {
		return md5(char)
	};
	// toast提示      this.$tools.showToast(字符串, 延时,图标（可选）)
	static showToast(txt, duration, icon) {
		uni.hideToast()
		uni.showToast({
			icon: icon || 'none',
			title: txt,
			duration: duration
		});
	};
	// 时间格式转换
	static dateFormat(date, fmt) {
		var o = {
			"M+": date.getMonth() + 1, //月份
			"d+": date.getDate(), //日
			"h+": date.getHours(), //小时
			"m+": date.getMinutes(), //分
			"s+": date.getSeconds(), //秒
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度
			"S": date.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
					.length)));
		return fmt;
	}
	//跳转需要登录的页面
	static goPage(url) {
		if (!flag) {
			flag = true
			let token = $cache.get('token')
			console.log(token, '放松放松')
			if (token == null || token == "undefind" || token == "" || token == "null" || token == "NULL" ||
				token == false) {
				uni.navigateTo({
					url: '/pages/login/login',
					success: () => {
						flag = false;
					},
				})
			} else {
				uni.navigateTo({
					url: url,
					animationType: 'slide-in-bottom',
					animationDuration: 100,
					success: () => {
						flag = false;
					},
				})
			}
		}
	}
	// 跳转不需要登录的页面       this.$tools.goPageNoAuth('/pages/xxxx')
	static goPageNoAuth(url) {
		uni.hideToast()
		if (!flag) {
			flag = true
			uni.navigateTo({
				url: url,
				animationType: 'slide-in-bottom',
				animationDuration: 100,
				success: () => {
					flag = false;
				},
			})
		}
		
	}
	/**
	 * 查看权限
	 * @param {Object} type 权限类型    
	 * @param {Object} chooseType	权限类型汉字
	 */
	static async dawdad(type, chooseType) {
		let andRes;
		if (plus.os.name == 'Android') {
			if (type === 'location') {
				andRes = await permision.checkSystemEnableLocation()
			} else {
				andRes = await permision.requestAndroidPermission(type)
			}
			if (!andRes) tools.goPage('/pages/common/permission?title=' + encodeURIComponent(chooseType))
		}
		return andRes;
	}
	/**
	 * 选择图片、视频
	 * 关于权限判断 iOS的机制是，你的代码真的调用了权限（不是判断权限），在系统设置里才会出现你的app 所以这里ios屏蔽了判断代码
	 * @param {Object} type			打开类型 1 仅相册 2 仅拍照 3 全部
	 * @param {Object} chooseType	选择类型 1 图片 2 视频
	 * @param {Object} count		选择个数
	 */
	static chooseImg(type, chooseType, count) {
		return new Promise(async (resolve, reject) => {
			// 检查权限
			var result = true;
			var title;
			if (type == 1) {
				// 相册
				if (plus.os.name == 'Android') {
					let andRes = await permision.requestAndroidPermission(
						'android.permission.READ_EXTERNAL_STORAGE')
					result = (andRes == 1)
					title = '存储'
				} else {
					// result = permision.judgeIosPermission('photoLibrary')
					// title = '相册'
				}
			} else if (type == 2) {
				// 相机
				if (plus.os.name == 'Android') {
					let andRes = await permision.requestAndroidPermission('android.permission.CAMERA')
					result = (andRes == 1)
				} else {
					// result = permision.judgeIosPermission('camera')
				}
				title = '摄像头'
			} else {
				// 相册
				if (plus.os.name == 'Android') {
					let andRes = await permision.requestAndroidPermission(
						'android.permission.READ_EXTERNAL_STORAGE')
					result = (andRes == 1)
					title = '存储'
				} else {
					// result = permision.judgeIosPermission('photoLibrary')
					// title = '相册'
				}


				if (result) {
					if (plus.os.name == 'Android') {
						let andRes = await permision.requestAndroidPermission(
							'android.permission.CAMERA')
						result = (andRes == 1)
					} else {
						// result = permision.judgeIosPermission('camera')
					}
					title = '摄像头'
				}
			}
			// // 如果没有权限 跳转到权限页面
			// if (!result) {
			// 	resolve(false)
			// 	uni.navigateTo({
			// 		url: '/pages/common/permission?title=' + encodeURIComponent(title)
			// 	})
			// 	return
			// }


			let types = []
			if (type == 1) {
				types = ['album']
			}
			if (type == 2) {
				types = ['camera']
			}

			if (chooseType == 1) {
				// 选择图片
				uni.chooseImage({
					count: count,
					sizeType: ['original', 'compressed'],
					sourceType: types, //从相册选择
					success: chooseImageRes => {
						const tempFilePaths = chooseImageRes.tempFiles
						tempFilePaths.forEach(item => {
							let path = item.path
							if (path.split('.')[path.split('.').length - 1] ==
								'gif') {
								tools.showToast({
									title: '不允许选择gif图',
									icon: 'none',
									duration: 1000
								})
								resolve(false)
								return
							}

							// ＞5M
							if (item.size > 5242880) {
								tools.showToast({
									title: '图片不能超过5Mb!',
									icon: 'none',
									duration: 1000
								})
								resolve(false)
								return
							}
						})
						resolve(chooseImageRes.tempFiles)
					}
				})
			} else {
				// 选择视频
				uni.chooseVideo({
					sourceType: types,
					maxDuration: 60,
					success: (res) => {
						const tempFilePaths = res.tempFilePath
						if (res.size > 314572800) {
							tools.showToast({
								title: '视频不能超过300Mb!',
								icon: 'none',
								duration: 1000
							})
							return
						}
						resolve(res.tempFilePath)
					}
				});
			}
		})
	}
	/**
	 * 上传文件
	 * @param {Object} file		文件参数
	 */
	static uploadFile(file,type) {
		return new Promise(async (resolve, reject) => {			
    	uni.uploadFile({
				url:baseurl +'/universal/uploadCloud',
				filePath:file,
				name: 'file',
				header:{
					'Authorization': uni.getStorageSync('token'),
				},
				formData: {
					'type': type
				},
				success: (res) => {
					console.log('回调回调回调回调', res);
						resolve(JSON.parse(res.data).result)  
				}
			});
		})

	}
	/**
	 * 计算年龄
	 * @param {Object} birthday		生日日期
	 */
	static mymethod(birthday) { //根据日期算年龄
		if (birthday) {
			birthday = birthday.split('-');
			// 新建日期对象
			let date = new Date();
			// 今天日期，数组，同 birthday
			let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
			// 分别计算年月日差值
			let age = today.map((val, index) => {
				return val - birthday[index]
			})
			// 当天数为负数时，月减 1，天数加上月总天数
			if (age[2] < 0) {
				// 简单获取上个月总天数的方法，不会错
				let lastMonth = new Date(today[0], today[1], 0)
				age[1]--
				age[2] += lastMonth.getDate()
			}
			// 当月数为负数时，年减 1，月数加上 12
			if (age[1] < 0) {
				age[0]--
				age[1] += 12
			}
			console.log(age[0] + '岁' + age[1] + '月' + age[2] + '天');
			return age[0] + '岁';
		}

	}
	/**
	 * 计算时间
	 * @param {Object} time		时间戳
	 */
	static fileTime(time) {
		const date = new Date(time)
		const Y = date.getFullYear()
		const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
		const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
		const h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
		const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
		const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
		// Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
		return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s

	}
}

export default tools;